<template>
  <div >
    <el-card shadow="hover" class="custom-card">
      <div class="card-content">
        <div class="card-left">
          <div class="card-title">
            <i class="el-icon-collection-tag"></i>
            成果全景分析
          </div>
          <el-tabs v-model="activeName" @tab-click="handleClick" type="card" class="custom-tabs">
            <el-tab-pane label="专利" name="first">
               <el-row :gutter="20">
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">增长趋势</div>
                    </div>
                    <div ref="patentChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">类型分布</div>
                    </div>
                    <div ref="typeChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">状态分布</div>
                    </div>
                    <div ref="statusChart" class="chart-container"></div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="软著" name="second">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">增长趋势</div>
                    </div>
                    <div ref="softwarChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">取得方式</div>
                    </div>
                    <div ref="softwarTypeChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">状态分布</div>
                    </div>
                    <div ref="softwarStatusChart" class="chart-container"></div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="论文" name="third">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">增长趋势</div>
                    </div>
                    <div ref="paperChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">期刊类型分布</div>
                    </div>
                    <div ref="paperTypeChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">状态分布</div>
                    </div>
                    <div ref="paperStatusChart" class="chart-container"></div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="标准" name="fourth">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">增长趋势</div>
                    </div>
                    <div ref="standardChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <el-col :span="12">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">标准级别分布</div>
                    </div>
                    <div ref="standardTypeChart" class="chart-container"></div>
                  </el-card>
                </el-col>
                <!-- <el-col :span="8">
                  <el-card shadow="never" class="inner-card">
                    <div class="chart-header">
                      <div class="chart-title">合作类型分布</div>
                    </div>
                    <div ref="standardStatusChart" class="chart-container"></div>
                  </el-card>
                </el-col> -->
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>


import * as echarts from 'echarts';
import { getPatentsByYearWithGrowth, getPatentsByType, getPatentsByApplicationStatus } from "@/api/sci/patent";
import { countSoftwareCopyrightsByYear, countSoftwareCopyrightsByRightsAcquisition, countSoftwareCopyrightsByApplicationStatus } from "@/api/sci/copyright";
import { getPaperAnnualStats, getPaperStatsByJournalType, getPaperStatsByPublishStatus } from "@/api/sci/paper";
import { getStandardAnnualStats, getStandardStatsByLevel } from "@/api/sci/standard";



export default {
  name: "AchvOverview",
  components: {

  },
  data() {
    return {
      activeName: 'first',  // 默认激活的标签页
      patentChart: null,
      typeChart: null,
      statusChart: null,
      patentData: [],
      typeData: [],
      statusData: [],

       // 软著图表实例
      softwarChart: null,
      softwarTypeChart: null,
      softwarStatusChart: null,
      // 软著数据
      softwarData: [],
      softwarTypeData: [],
      softwarStatusData: [],
      // 标记软著数据是否已加载
      softwarDataLoaded: false,


      // 论文图表实例
      paperChart: null,
      paperTypeChart: null,
      paperStatusChart: null,
      // 论文数据
      paperData: [],
      paperTypeData: [],
      paperStatusData: [],
      // 标记论文数据是否已加载
      paperDataLoaded: false,
       // 标准图表实例
      standardChart: null,
      standardTypeChart: null,
      standardStatusChart: null,
      // 标准数据
      standardData: [],
      standardTypeData: [],
      standardStatusData: [],
      // 标记标准数据是否已加载
      standardDataLoaded: false

    };
  },
  computed: {

  },
  created() {
    this.fetchAllData();
  },
  mounted() {
    this.initCharts();
  },
  watch: {},
  methods: {
    async fetchAllData() {
      try {
        // 获取所有数据
        const [patentRes, typeRes, statusRes] = await Promise.all([
          getPatentsByYearWithGrowth(),
          getPatentsByType(),
          getPatentsByApplicationStatus()
        ]);

        this.patentData = patentRes.data;
        this.typeData = typeRes.data;
        this.statusData = statusRes.data;

        this.$nextTick(() => {
          this.updatePatentChart();
          this.updateTypeChart();
          this.updateStatusChart();
        });
      } catch (error) {
        console.error("获取数据失败:", error);
        this.$message.error("获取数据失败");
      }
    },
    // 获取软著数据
    async fetchSoftwarData() {
      if (this.softwarDataLoaded) return; // 如果已经加载过数据，则不再重复加载

      try {
        // 获取软著所有数据
        const [softwarRes, softwarTypeRes, softwarStatusRes] = await Promise.all([
          countSoftwareCopyrightsByYear(),
          countSoftwareCopyrightsByRightsAcquisition(),
          countSoftwareCopyrightsByApplicationStatus()
        ]);

        this.softwarData = softwarRes.data;
        this.softwarTypeData = softwarTypeRes.data;
        this.softwarStatusData = softwarStatusRes.data;
        this.softwarDataLoaded = true; // 标记数据已加载

        this.$nextTick(() => {
          this.updateSoftwarChart();
          this.updateSoftwarTypeChart();
          this.updateSoftwarStatusChart();
        });
      } catch (error) {
        console.error("获取软著数据失败:", error);
        this.$message.error("获取软著数据失败");
      }
    },

    // 获取论文数据
    async fetchPaperData() {
      if (this.paperDataLoaded) return; // 如果已经加载过数据，则不再重复加载

      try {
        // 获取论文所有数据
        const [paperRes, paperTypeRes, paperStatusRes] = await Promise.all([
          getPaperAnnualStats(),
          getPaperStatsByJournalType(),
          getPaperStatsByPublishStatus()
        ]);

        this.paperData = paperRes.rows;
        this.paperTypeData = paperTypeRes.rows;
        this.paperStatusData = paperStatusRes.rows;
        this.paperDataLoaded = true; // 标记数据已加载

        this.$nextTick(() => {
          this.updatePaperChart();
          this.updatePaperTypeChart();
          this.updatePaperStatusChart();
        });
      } catch (error) {
        console.error("获取论文数据失败:", error);
        this.$message.error("获取论文数据失败");
      }
    },

     // 获取标准数据
    async fetchStandardData() {
      if (this.standardDataLoaded) return; // 如果已经加载过数据，则不再重复加载

      try {
        // 获取标准所有数据
        const [standardRes, standardTypeRes] = await Promise.all([
          getStandardAnnualStats(),
          getStandardStatsByLevel()
        ]);

        this.standardData = standardRes.rows;
        this.standardTypeData = standardTypeRes.rows;
        this.standardDataLoaded = true; // 标记数据已加载

        this.$nextTick(() => {
          this.updateStandardChart();
          this.updateStandardTypeChart();
        });
      } catch (error) {
        console.error("获取标准数据失败:", error);
        this.$message.error("获取标准数据失败");
      }
    },

    initCharts() {
      this.patentChart = echarts.init(this.$refs.patentChart);
      this.typeChart = echarts.init(this.$refs.typeChart);
      this.statusChart = echarts.init(this.$refs.statusChart);

      this.updatePatentChart();
      this.updateTypeChart();
      this.updateStatusChart();

      // 监听窗口变化，自适应调整图表大小
      window.addEventListener('resize', this.handleResize);
    },

     // 初始化软著图表
    initSoftwarCharts() {
      if (!this.softwarChart) {
        this.softwarChart = echarts.init(this.$refs.softwarChart);
      }
      if (!this.softwarTypeChart) {
        this.softwarTypeChart = echarts.init(this.$refs.softwarTypeChart);
      }
      if (!this.softwarStatusChart) {
        this.softwarStatusChart = echarts.init(this.$refs.softwarStatusChart);
      }

      this.updateSoftwarChart();
      this.updateSoftwarTypeChart();
      this.updateSoftwarStatusChart();
    },


     // 初始化论文图表
    initPaperCharts() {
      if (!this.paperChart) {
        this.paperChart = echarts.init(this.$refs.paperChart);
      }
      if (!this.paperTypeChart) {
        this.paperTypeChart = echarts.init(this.$refs.paperTypeChart);
      }
      if (!this.paperStatusChart) {
        this.paperStatusChart = echarts.init(this.$refs.paperStatusChart);
      }

      this.updatePaperChart();
      this.updatePaperTypeChart();
      this.updatePaperStatusChart();
    },

    // 初始化标准图表
    initStandardCharts() {
      if (!this.standardChart) {
        this.standardChart = echarts.init(this.$refs.standardChart);
      }
      if (!this.standardTypeChart) {
        this.standardTypeChart = echarts.init(this.$refs.standardTypeChart);
      }
      if (!this.standardStatusChart) {
        this.standardStatusChart = echarts.init(this.$refs.standardStatusChart);
      }

      this.updateStandardChart();
      this.updateStandardTypeChart();
    },

    handleClick(tab, event) {

      // 处理标签页切换
      if (tab.name === 'second' && !this.softwarDataLoaded) {
        // 切换到软著tab且数据未加载时，获取软著数据
        this.$nextTick(() => {
          this.initSoftwarCharts();
        });
        this.fetchSoftwarData();
      } else if (tab.name === 'second' && this.softwarDataLoaded) {
        // 切换到软著tab且数据已加载时，初始化图表
        this.$nextTick(() => {
          this.initSoftwarCharts();
        });
      }else if (tab.name === 'third' && !this.paperDataLoaded) {
        // 切换到论文tab且数据未加载时，获取论文数据
         this.$nextTick(() => {
          this.initPaperCharts();
        });
        this.fetchPaperData();
      } else if (tab.name === 'third' && this.paperDataLoaded) {
        // 切换到论文tab且数据已加载时，初始化图表
        this.$nextTick(() => {
          this.initPaperCharts();
        });
      }
      else if (tab.name === 'fourth' && !this.standardDataLoaded) {
        // 切换到标准tab且数据未加载时，获取标准数据
        this.$nextTick(() => {
          this.initStandardCharts();
        });
        this.fetchStandardData();
      } else if (tab.name === 'fourth' && this.standardDataLoaded) {
        // 切换到标准tab且数据已加载时，初始化图表
        this.$nextTick(() => {
          this.initStandardCharts();
        });
      }
    },


    // 获取响应式饼图半径
    getResponsiveRadius(chartRef) {
      if (!this.$refs || !chartRef) return '75%';

      const chartWidth = chartRef.offsetWidth;

      if (chartWidth < 400) {
        return '30%'; // 小屏幕
      } else if (chartWidth < 600) {
        return '60%'; // 中等屏幕
      } else {
        return '75%'; // 大屏幕
      }
    },

    // 获取响应式字体大小
    getResponsiveFontSize(chartRef) {
      if (!this.$refs || !chartRef) return 12;

      const chartWidth = chartRef.offsetWidth;

      if (chartWidth < 400) {
        return 10; // 小屏幕
      } else if (chartWidth < 600) {
        return 11; // 中等屏幕
      } else {
        return 12; // 大屏幕
      }
    },

    // 获取响应式标签线长度
    getResponsiveLineLength(chartRef) {
      if (!this.$refs || !chartRef) return 10;

      const chartWidth = chartRef.offsetWidth;

      if (chartWidth < 400) {
        return 5; // 小屏幕
      } else if (chartWidth < 600) {
        return 8; // 中等屏幕
      } else {
        return 10; // 大屏幕
      }
    },

    // 获取响应式标签线第二段长度
    getResponsiveLineLength2(chartRef) {
      if (!this.$refs || !chartRef) return 15;

      const chartWidth = chartRef.offsetWidth;

      if (chartWidth < 400) {
        return 10; // 小屏幕
      } else if (chartWidth < 600) {
        return 12; // 中等屏幕
      } else {
        return 15; // 大屏幕
      }
    },

    // 更新图表尺寸的响应式方法
    updateChartSize() {
      if (this.typeChart) {
        // 重新计算并设置图表选项
        const currentOption = this.typeChart.getOption();
        if (currentOption && currentOption.series && currentOption.series[0]) {
          currentOption.series[0].radius = this.getResponsiveRadius();
          currentOption.series[0].label.textStyle.fontSize = this.getResponsiveFontSize();
          currentOption.series[0].label.rich.name.fontSize = this.getResponsiveFontSize();
          currentOption.series[0].label.rich.value.fontSize = this.getResponsiveFontSize();
          currentOption.series[0].label.rich.percent.fontSize = this.getResponsiveFontSize();
          currentOption.series[0].labelLine.length = this.getResponsiveLineLength();
          currentOption.series[0].labelLine.length2 = this.getResponsiveLineLength2();

          this.typeChart.setOption(currentOption, true);
        }
        this.typeChart.resize();
      }
    },

    handleResize() {
      if (this.patentChart) {
        this.patentChart.resize();
      }
      if (this.typeChart) {
        this.typeChart.resize();
      }
      if (this.statusChart) {
        this.statusChart.resize();
      }

      // 软著图表resize
      if (this.softwarChart) {
        this.softwarChart.resize();
      }
      if (this.softwarTypeChart) {
        this.softwarTypeChart.resize();
      }
      if (this.softwarStatusChart) {
        this.softwarStatusChart.resize();
      }

      // 论文图表resize
      if (this.paperChart) {
        this.paperChart.resize();
      }
      if (this.paperTypeChart) {
        this.paperTypeChart.resize();
      }
      if (this.paperStatusChart) {
        this.paperStatusChart.resize();
      }

      // 标准图表resize
      if (this.standardChart) {
        this.standardChart.resize();
      }
      if (this.standardTypeChart) {
        this.standardTypeChart.resize();
      }
      if (this.standardStatusChart) {
        this.standardStatusChart.resize();
      }
    },


    getChartColors() {
      return ['#267FF7', '#7AB8FF', '#599EEC', '#3673E8'];
    },

    // 通用tooltip配置
    getCommonTooltip() {
      return {
        backgroundColor: 'rgba(38, 127, 247, 0.15)', // 淡蓝色背景
        borderColor: 'rgba(64, 158, 255, 0.3)', // 边框颜色
        borderWidth: 1,
        padding: 10,
        textStyle: {
          color: '#000',
          fontSize: 12
        },
        extraCssText: 'backdrop-filter: blur(10px); border-radius: 8px; box-shadow: 0 0 20px rgba(64, 158, 255, 0.3);'
      };
    },

    // 通用饼图tooltip格式化器
    getPieTooltipFormatter() {
      return (param) => {
        return `<div style="padding: 8px 12px; background: rgba(255, 255, 255, 0.1); border-radius: 6px; margin-bottom: 8px; font-weight: bold; text-align: center;">${param.name}</div>
                <div style="padding: 6px 10px; background: ${param.color}; border-radius: 5px; display: flex; justify-content: space-between; align-items: center;">
                  <div>
                    <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${param.color}; margin-right: 6px;"></span>
                    <span style="color:#ffffff">数量</span>
                  </div>
                  <span style="font-weight: bold; font-size: 14px; color: #ffffff; text-shadow: 0 0 4px rgba(255, 255, 255, 0.8); margin-left: 15px;">${param.value}</span>
                </div>`;
      };
    },

    // 通用折线/柱状图tooltip格式化器
    getAxisTooltipFormatter() {
      return (params) => {
        let tooltipText = `<div style="padding: 8px 12px; background: rgba(255, 255, 255, 0.1); border-radius: 6px; margin-bottom: 8px; font-weight: bold; text-align: center;">${params[0].name}</div>`;
        params.forEach(param => {
          // 处理undefined值，显示为空
          const value = param.value === undefined || param.value === null ? '' : param.value;

          if (param.seriesName === '增长率') {
            tooltipText += `<div style="padding: 6px 10px; background: #7AB8FF; border-radius: 5px; margin-bottom: 6px; display: flex; justify-content: space-between; align-items: center;">
              <div>
                <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${param.color}; margin-right: 6px;"></span>
                <span style="color: #ffffff;">${param.seriesName}</span>
              </div>
              <span style="font-weight: bold; font-size: 14px; color: #ffffff; text-shadow: 0 0 4px rgba(255, 255, 255, 0.8); margin-left: 15px;">${value}${param.seriesName === '增长率' && value !== '' ? '%' : ''}</span>
            </div>`;
          } else {
            tooltipText += `<div style="padding: 6px 10px; background: #267FF7; border-radius: 5px; margin-bottom: 6px; display: flex; justify-content: space-between; align-items: center;">
              <div>
                <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${param.color}; margin-right: 6px;"></span>
                <span style="color: #ffffff;">${param.seriesName}</span>
              </div>
              <span style="font-weight: bold; font-size: 14px; color: #ffffff; text-shadow: 0 0 4px rgba(255, 255, 255, 0.8); margin-left: 15px;">${value}</span>
            </div>`;
          }
        });
        return tooltipText;
      };
    },

    // 通用饼图配置
    getCommonPieConfig(chartRef) {
      return {
        color: this.getChartColors(),
        tooltip: {
          ...this.getCommonTooltip(),
          trigger: 'item',
          formatter: this.getPieTooltipFormatter()
        },
        series: [
          {
            type: 'pie',
            radius: this.getResponsiveRadius(chartRef),
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        ]
      };
    },

    // 通用柱状/折线图配置
    getCommonAxisConfig() {
      return {
        color: this.getChartColors(),
        tooltip: {
          ...this.getCommonTooltip(),
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        }
      };
    },

    // 通用饼图标签配置
    getPieLabelConfig(chartRef, data, valueField) {
      return {
        show: true,
        formatter: (params) => {
          // 获取当前项的值
          const value = params.value || 0;

          // 计算总值
          const total = data.reduce((sum, item) => sum + (item[valueField] || 0), 0);

          // 计算百分比
          const percentage = total ? ((value / total) * 100).toFixed(1) : 0;

          // 返回带格式的标签文本
          return `{name|${params.name}}{gap| }{value|${value}}{gap| }{percent|${percentage}%}`;
        },
        position: 'outside',
        alignTo: 'none',
        bleedMargin: 5,
        distanceToLabelLine: 5,
        textStyle: {
          fontSize: this.getResponsiveFontSize(chartRef)
        },
        rich: {
          name: {
            color: '#666666',
            fontSize: this.getResponsiveFontSize(chartRef),
            padding: [0, 0, 0, 0]
          },
          value: {
            color: '#2559B2',
            fontSize: this.getResponsiveFontSize(chartRef),
            fontWeight: 'bold',
            textShadowColor: 'rgba(37, 89, 178, 0.3)',
            textShadowBlur: 2,
            textShadowOffsetX: 1,
            textShadowOffsetY: 1,
            padding: [0, 5, 0, 5]
          },
          percent: {
            color: '#999999',
            fontSize: this.getResponsiveFontSize(chartRef),
            fontWeight: 'bold',
            padding: [0, 0, 0, 5]
          },
          gap: {
            width: 4,
            height: 14,
            backgroundColor: 'transparent'
          }
        }
      };
    },

    // 通用饼图标签线配置
    getPieLabelLineConfig(chartRef) {
      return {
        show: true,
        length: this.getResponsiveLineLength(chartRef),
        length2: this.getResponsiveLineLength2(chartRef)
      };
    },

    // 通用X轴配置
    getCommonXAxis(data) {
      return {
        type: 'category',
        data: data,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          fontSize: 12
        },
        splitLine: {
          show: false
        }
      };
    },

    // 通用Y轴配置
    getCommonYAxis(name, isPercent = false) {
      return {
        type: 'value',
        name: name,
        min: 0,
        axisLabel: {
          formatter: isPercent ? '{value}%' : '{value}'
        },
        splitLine: {
          show: false
        }
      };
    },

    // 通用增长率Y轴配置
    getGrowthRateYAxis() {
      return {
        type: 'value',
        name: '增长率(%)',
        min: 0,
        axisLabel: {
          formatter: '{value}%'
        },
        splitLine: {
          show: false
        }
      };
    },

    // 更新专利增长趋势图表
    updatePatentChart() {
      if (!this.patentChart || !this.patentData.length) return;

      // 提取数据
      const years = this.patentData.map(item => item.statistical_year);
      const counts = this.patentData.map(item => item.patent_count);
      const growthRates = this.patentData.map(item => item.growth_rate_percent);

      // 使用通用配置
      const option = {
        ...this.getCommonAxisConfig(),
        tooltip: {
          ...this.getCommonAxisConfig().tooltip,
          formatter: this.getAxisTooltipFormatter()
        },
        legend: {
          data: ['专利数量', '增长率'],
          bottom: '0',
          left: 'center'
        },
        xAxis: [this.getCommonXAxis(years)],
        yAxis: [
          this.getCommonYAxis('专利数量'),
          this.getGrowthRateYAxis()
        ],
        series: [
          {
            name: '专利数量',
            type: 'bar',
            data: counts,
            barMaxWidth: 50,
          },
          {
            name: '增长率',
            type: 'line',
            yAxisIndex: 1,
            data: growthRates,
            smooth: true,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(122, 184, 255, 0.8)'
                }, {
                  offset: 1, color: 'rgba(122, 184, 255, 0.1)'
                }]
              }
            },
            itemStyle: {
              color: '#7AB8FF'
            }
          }
        ]
      };

      this.patentChart.setOption(option);
    },

    // 更新专利类型分布图表
    updateTypeChart() {
      if (!this.typeChart || !this.typeData.length) return;

      // 提取数据
      const types = this.typeData.map(item => item.patent_type);
      const counts = this.typeData.map(item => item.patent_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.typeChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: types
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.typeChart).series[0],
            name: '专利类型',
            label: this.getPieLabelConfig(this.$refs.typeChart, this.typeData, 'patent_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.typeChart),
            data: types.map((type, index) => ({
              name: type,
              value: counts[index]
            }))
          }
        ]
      };

      this.typeChart.setOption(option);
    },

    // 更新专利状态分布图表
    updateStatusChart() {
      if (!this.statusChart || !this.statusData.length) return;

      // 提取数据
      const statuses = this.statusData.map(item => item.application_status);
      const counts = this.statusData.map(item => item.patent_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.statusChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: statuses
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.statusChart).series[0],
            name: '申请状态',
            label: this.getPieLabelConfig(this.$refs.statusChart, this.statusData, 'patent_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.statusChart),
            data: statuses.map((status, index) => ({
              name: status,
              value: counts[index]
            }))
          }
        ]
      };

      this.statusChart.setOption(option);
    },

    // 更新软著增长趋势图表
    updateSoftwarChart() {
      if (!this.softwarChart || !this.softwarData.length) return;

      // 提取数据
      const years = this.softwarData.map(item => item.statistical_year);
      const counts = this.softwarData.map(item => item.software_count);
      const growthRates = this.softwarData.map(item => item.growth_rate_percent);

      // 使用通用配置
      const option = {
        ...this.getCommonAxisConfig(),
        tooltip: {
          ...this.getCommonAxisConfig().tooltip,
          formatter: this.getAxisTooltipFormatter()
        },
        legend: {
          data: ['软著数量', '增长率'],
          bottom: '0',
          left: 'center'
        },
        xAxis: [this.getCommonXAxis(years)],
        yAxis: [
          this.getCommonYAxis('软著数量'),
          this.getGrowthRateYAxis()
        ],
        series: [
          {
            name: '软著数量',
            type: 'bar',
            data: counts,
            barMaxWidth: 50,
          },
          {
            name: '增长率',
            type: 'line',
            yAxisIndex: 1,
            data: growthRates,
            smooth: true,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(122, 184, 255, 0.8)'
                }, {
                  offset: 1, color: 'rgba(122, 184, 255, 0.1)'
                }]
              }
            },
            itemStyle: {
              color: '#7AB8FF'
            }
          }
        ]
      };

      this.softwarChart.setOption(option);
    },

    // 更新软著取得方式图表
    updateSoftwarTypeChart() {
      if (!this.softwarTypeChart || !this.softwarTypeData.length) return;

      // 提取数据
      const types = this.softwarTypeData.map(item => item.rights_acquisition);
      const counts = this.softwarTypeData.map(item => item.software_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.softwarTypeChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: types
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.softwarTypeChart).series[0],
            name: '取得方式',
            label: this.getPieLabelConfig(this.$refs.softwarTypeChart, this.softwarTypeData, 'software_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.softwarTypeChart),
            data: types.map((type, index) => ({
              name: type,
              value: counts[index]
            }))
          }
        ]
      };

      this.softwarTypeChart.setOption(option);
    },

    // 更新软著状态分布图表
    updateSoftwarStatusChart() {
      if (!this.softwarStatusChart || !this.softwarStatusData.length) return;

      // 提取数据
      const statuses = this.softwarStatusData.map(item => item.application_status);
      const counts = this.softwarStatusData.map(item => item.software_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.softwarStatusChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: statuses
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.softwarStatusChart).series[0],
            name: '申请状态',
            label: this.getPieLabelConfig(this.$refs.softwarStatusChart, this.softwarStatusData, 'software_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.softwarStatusChart),
            data: statuses.map((status, index) => ({
              name: status,
              value: counts[index]
            }))
          }
        ]
      };

      this.softwarStatusChart.setOption(option);
    },

    // 更新论文增长趋势图表
    updatePaperChart() {
      if (!this.paperChart || !this.paperData.length) return;

      // 提取数据
      const years = this.paperData.map(item => item.statistical_year);
      const counts = this.paperData.map(item => item.paper_count);
      const growthRates = this.paperData.map(item => item.growth_rate_percent);

      // 使用通用配置
      const option = {
        ...this.getCommonAxisConfig(),
        tooltip: {
          ...this.getCommonAxisConfig().tooltip,
          formatter: this.getAxisTooltipFormatter()
        },
        legend: {
          data: ['论文数量', '增长率'],
          bottom: '0',
          left: 'center'
        },
        xAxis: [this.getCommonXAxis(years)],
        yAxis: [
          this.getCommonYAxis('论文数量'),
          this.getGrowthRateYAxis()
        ],
        series: [
          {
            name: '论文数量',
            type: 'bar',
            data: counts,
            barMaxWidth: 50,
          },
          {
            name: '增长率',
            type: 'line',
            yAxisIndex: 1,
            data: growthRates,
            smooth: true,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(122, 184, 255, 0.8)'
                }, {
                  offset: 1, color: 'rgba(122, 184, 255, 0.1)'
                }]
              }
            },
            itemStyle: {
              color: '#7AB8FF'
            }
          }
        ]
      };

      this.paperChart.setOption(option);
    },

    // 更新论文期刊类型分布图表
    updatePaperTypeChart() {
      if (!this.paperTypeChart || !this.paperTypeData.length) return;

      // 提取数据
      const types = this.paperTypeData.map(item => item.journal_type);
      const counts = this.paperTypeData.map(item => item.patent_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.paperTypeChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: types
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.paperTypeChart).series[0],
            name: '期刊类型',
            label: this.getPieLabelConfig(this.$refs.paperTypeChart, this.paperTypeData, 'patent_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.paperTypeChart),
            data: types.map((type, index) => ({
              name: type,
              value: counts[index]
            }))
          }
        ]
      };

      this.paperTypeChart.setOption(option);
    },

    // 更新论文发表状态分布图表
    updatePaperStatusChart() {
      if (!this.paperStatusChart || !this.paperStatusData.length) return;

      // 提取数据
      const statuses = this.paperStatusData.map(item => item.publish_status);
      const counts = this.paperStatusData.map(item => item.paper_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.paperStatusChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: statuses
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.paperStatusChart).series[0],
            name: '发表状态',
            label: this.getPieLabelConfig(this.$refs.paperStatusChart, this.paperStatusData, 'paper_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.paperStatusChart),
            data: statuses.map((status, index) => ({
              name: status,
              value: counts[index]
            }))
          }
        ]
      };

      this.paperStatusChart.setOption(option);
    },

    // 更新标准增长趋势图表
    updateStandardChart() {
      if (!this.standardChart || !this.standardData.length) return;

      // 提取数据
      const years = this.standardData.map(item => item.statistical_year);
      const counts = this.standardData.map(item => item.standard_count);
      const growthRates = this.standardData.map(item => item.growth_rate_percent);

      // 使用通用配置
      const option = {
        ...this.getCommonAxisConfig(),
        tooltip: {
          ...this.getCommonAxisConfig().tooltip,
          formatter: this.getAxisTooltipFormatter()
        },
        legend: {
          data: ['标准数量', '增长率'],
          bottom: '0',
          left: 'center'
        },
        xAxis: [this.getCommonXAxis(years)],
        yAxis: [
          this.getCommonYAxis('标准数量'),
          this.getGrowthRateYAxis()
        ],
        series: [
          {
            name: '标准数量',
            type: 'bar',
            data: counts,
            barMaxWidth: 50,
          },
          {
            name: '增长率',
            type: 'line',
            yAxisIndex: 1,
            data: growthRates,
            smooth: true,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(122, 184, 255, 0.8)'
                }, {
                  offset: 1, color: 'rgba(122, 184, 255, 0.1)'
                }]
              }
            },
            itemStyle: {
              color: '#7AB8FF'
            }
          }
        ]
      };

      this.standardChart.setOption(option);
    },

    // 更新标准级别分布图表
    updateStandardTypeChart() {
      if (!this.standardTypeChart || !this.standardTypeData.length) return;

      // 提取数据
      const types = this.standardTypeData.map(item => item.standard_level);
      const counts = this.standardTypeData.map(item => item.standard_count);

      // 使用通用配置
      const option = {
        ...this.getCommonPieConfig(this.$refs.standardTypeChart),
        legend: {
          orient: 'horizontal',
          bottom: '0',
          data: types
        },
        series: [
          {
            ...this.getCommonPieConfig(this.$refs.standardTypeChart).series[0],
            name: '标准级别',
            label: this.getPieLabelConfig(this.$refs.standardTypeChart, this.standardTypeData, 'standard_count'),
            labelLine: this.getPieLabelLineConfig(this.$refs.standardTypeChart),
            data: types.map((type, index) => ({
              name: type,
              value: counts[index]
            }))
          }
        ]
      };

      this.standardTypeChart.setOption(option);
    }
  },
  beforeDestroy() {
      // 销毁图表实例，防止内存泄漏
      if (this.patentChart) {
        this.patentChart.dispose();
      }
      if (this.typeChart) {
        this.typeChart.dispose();
      }
      if (this.statusChart) {
        this.statusChart.dispose();
      }
      // 销毁软著图表实例
      if (this.softwarChart) {
        this.softwarChart.dispose();
      }
      if (this.softwarTypeChart) {
        this.softwarTypeChart.dispose();
      }
      if (this.softwarStatusChart) {
        this.softwarStatusChart.dispose();
      }
      // 销毁论文图表实例
      if (this.paperChart) {
        this.paperChart.dispose();
      }
      if (this.paperTypeChart) {
        this.paperTypeChart.dispose();
      }
      if (this.paperStatusChart) {
        this.paperStatusChart.dispose();
      }

      // 销毁标准图表实例
      if (this.standardChart) {
        this.standardChart.dispose();
      }
      if (this.standardTypeChart) {
        this.standardTypeChart.dispose();
      }
      if (this.standardStatusChart) {
        this.standardStatusChart.dispose();
      }
      window.removeEventListener('resize', this.handleResize);
    }
};
</script>

<style lang="scss" scoped>

  .chart-container {
    width: 100%;
    height: 350px;
  }

  .custom-card {
    border-radius: 8px;
    border: none;

    ::v-deep .el-card__body {
      padding: 20px;
    }
  }

  .card-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-left {
    flex: 1;
  }

  .card-title {
    color: #000000;
    font-size: 22px;
    margin-bottom: 16px;
    font-weight: bold;
    font-family: SimHei, sans-serif;
    display: flex;
    align-items: center;
    gap: 15px;
  }

  sub-card-title {
    color: #000000;
    font-size: 16px;
    margin-bottom: 16px;
    font-weight: bold;
    font-family: SimHei, sans-serif;
    display: flex;
    align-items: center;
    gap: 15px;
  }

  ::v-deep .custom-tabs {
    .el-tabs__header {
      margin-bottom: 20px;
      border-bottom: 1px solid #e4e7ed;
    }

    .el-tabs__nav {
      border: none;
    }

    .el-tabs__item {
      height: 40px;
      line-height: 40px;
      padding: 0 25px;
      border: 1px solid #e4e7ed;
      border-radius: 6px 6px 0 0;
      margin-right: 10px;
      color: #606266;
      background-color: #f5f7fa;
      transition: all 0.3s;

      &.is-active {
        color: #409eff;
        background-color: #ffffff;
        border-bottom-color: #ffffff;
        font-weight: bold;
      }

      &:not(.is-active):hover {
        color: #409eff;
        background-color: #ffffff;
      }
    }

    .el-tabs__active-bar {
      display: none;
    }

    .el-tabs__content {
      min-height: 300px;
    }
  }

  .inner-card {
    // border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    ::v-deep .el-card__body {
      padding: 15px;
    }
  }

  .chart-header {
    margin-bottom: 15px;

    .chart-title {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
      font-family: 'Microsoft YaHei', sans-serif;
      display: flex;
      align-items: center;

      &::before {
        content: '';
        display: inline-block;
        width: 4px;
        height: 20px;
        background: linear-gradient(to bottom, #409EFF, #1067DE);
        border-radius: 2px;
        margin-right: 10px;
        box-shadow: 2px 2px 4px rgba(64, 158, 255, 0.3);
      }
    }
  }


</style>
